/*
	The MIT License

	Copyright (c) 2008 IFMO/GameDev Studio

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
*/
// ui_frame_mgr.cpp - frame manager

#include "ui_local.h"

/*-----------------------------------------------------------------------------
	UI Node :
-----------------------------------------------------------------------------*/
static IUIFrame *stub_frame;

EUINode::EUINode(void)
{
	children.clear();
	frame	=	stub_frame;
	parent	=	NULL;
}


EUINode::~EUINode(void)
{
	for (uint i=0; i<children.size(); i++) {
		delete children[i];
	}
	children.clear();
}


void EUINode::AddChild(IUIFrame *new_frame)
{
	EUINode	*new_node = new EUINode;
	new_node->parent = this;
	new_node->frame	 = new_frame;
	children.push_back( new_node );
}


void EUINode::RemoveChild(EUINode *node)
{
	vector<EUINode*>::iterator vi;	
	for (vi = children.begin(); vi!=children.end(); vi++) {
		if (*vi == node) {
			children.erase(vi);
			delete node;
			return;
		}
	}
}


void EUINode::RemoveChild(EUINode *node, EUINode *new_parent)
{
	vector<EUINode*>::iterator vi;	
	for (vi = children.begin(); vi!=children.end(); vi++) {
		if (*vi == node) {
			children.erase(vi);
			break;
		}
	}

	node->parent = new_parent;	
	new_parent->children.push_back(node);
}


void EUINode::MoveChildBack(EUINode *node)
{
	vector<EUINode*>::iterator vi;	
	for (vi = children.begin(); vi!=children.end(); vi++) {
		if (*vi == node) {
			children.erase(vi);
			children.push_back(node);
			return;
		}
	}
}

/*-----------------------------------------------------------------------------
	Root Frame :
-----------------------------------------------------------------------------*/
EUIRootFrame::EUIRootFrame(class EUserInterface *ui)
{
	this->ui = ui;
}

EUIRootFrame::~EUIRootFrame(void)
{
	
}

void EUIRootFrame::FMMove(float new_x, float new_y)
{
	rect.x = new_x;
	rect.y = new_y;
}

void EUIRootFrame::FMResize(float new_width, float new_height)
{
	rect.w = new_width;
	rect.h = new_height;
}

void EUIRootFrame::FMPaint(void)
{
	// root frame should not draw anything!
}

/*-----------------------------------------------------------------------------
	UI Manager :
-----------------------------------------------------------------------------*/

//
//	EUserInterface::InitFrameManager
//
void EUserInterface::InitFrameManager(void)
{
	ui_root			=	new EUINode;
	ui_root->frame	=	new EUIRootFrame(this);
	
	uint w, h;
    rs->GetScreenSize(w, h);
	ui_root->frame->FMMove(0, 0);
	ui_root->frame->FMResize((float)w, (float)h);
	
	mb_down_frame[0] = NULL;
	mb_down_frame[1] = NULL;
	mb_down_frame[2] = NULL;
	frame_under_cursor = NULL;
	drag_frame	= NULL;
	
	active_frame  = NULL;
}


//
//	EUserInterface::ShutdownFrameManager
//
void EUserInterface::ShutdownFrameManager(void)
{
	delete ui_root->frame;
	delete ui_root;
}


/*-----------------------------------------------------------------------------
	Hierarchy stuff :
-----------------------------------------------------------------------------*/
//
//	EUserInterface::AttachFrame
//
void EUserInterface::AttachFrame(IUIFrame *parent, IUIFrame *frame)
{
	EUINode	*parent_node = 0;
	
	//	If parent frame is not specified, attach object to desktop :
	if (parent) {
		parent_node = FindFrameNode(parent->GetClientArea());
		ASSERT(parent_node);
	} else {
		parent_node = ui_root;
	}

	//  If frame was previosuly attached to any another frame,
	//	we should detach it first.	
	EUINode *frame_node = FindFrameNode(frame);
	if (frame_node) {
		EUINode *old_parent = frame_node->GetParent();
		old_parent->RemoveChild(frame_node, parent_node);
	} else {
		parent_node->AddChild(frame);
	}
}


//
//	EUserInterface::DetachFrame
//
void EUserInterface::DetachFrame(IUIFrame *frame)
{
	EUINode *node = FindFrameNode(frame);
	ASSERT(node);
	
	EUINode *parent = node->GetParent();
	ASSERT(parent);
	
	parent->RemoveChild(node);
}


//
//	EUserInterface::GetFrameChildNum
//
uint EUserInterface::GetFrameChildNum(IUIFrame *frame)
{
	EUINode *node = FindFrameNode(frame->GetClientArea());
	ASSERT(node);
	return node->GetChildNum();
}


//
//	EUserInterface::GetFrameChild
//
IUIFrame *EUserInterface::GetFrameChild(IUIFrame *frame, uint n)
{
	EUINode *node = FindFrameNode(frame->GetClientArea());
	ASSERT(node);
	
	return node->GetChild(n)->frame;
}


IUIFrame *EUserInterface::GetFrameParent(IUIFrame *frame)
{
	EUINode *node = FindFrameNode(frame);
	ASSERT(node);
	
	return node->GetParent()->frame;
}

/*-----------------------------------------------------------------------------
	Frame message stuff :
-----------------------------------------------------------------------------*/

void EUserInterface::EmitMouseEvents(void)
{
	mouseInput_s	*mi = &mouse_input;
	float mouse_x	= (float)mi->x;
	float mouse_y	= (float)mi->y;
	
	IUIFrame	*current_frame_uc = GetFrameUnderCursor();
	
	//
	//	Handle Mouse Button Events :
	//
	bool mb_down[3];
	bool mb_up[3];
	
	uint mbtn[3] = { UI_MOUSE_LEFT, UI_MOUSE_RIGHT, UI_MOUSE_MIDDLE };

	mb_down[0]	=	!old_mouse.left && mi->left;
	mb_up[0]	=	old_mouse.left && !mi->left;
	mb_down[1]	=	!old_mouse.right && mi->right;
	mb_up[1]	=	old_mouse.right && !mi->right;
	mb_down[2]	=	!old_mouse.middle && mi->middle;
	mb_up[2]	=	old_mouse.middle && !mi->middle;
	
	for (uint button=0; button<3; button++) {
		float x, y;
		GetAbsolutePosition( current_frame_uc, x, y);
		
		// MOUSE BUTTON DOWN :
		if (mb_down[button]) {
			//	send MouseDown message :
			if (current_frame_uc) {
				current_frame_uc->FMMouseDown(mbtn[button], mouse_x - x, mouse_y - y);
				
			}

			// we should remember frame to handle MouseClick :
			mb_down_frame[button]	=	current_frame_uc;
		}
		
		//	MOUSE BUTTON UP :
		if (mb_up[button]) {
		
			//	send MouseUp message :
			if (current_frame_uc) {
				current_frame_uc->FMMouseUp(mbtn[button], mouse_x - x, mouse_y - y);
			}

			//	handle MouseClick :
			if (current_frame_uc==mb_down_frame[button]) {

				if (current_frame_uc) {
					current_frame_uc->FMMouseClick(mbtn[button], mouse_x - x, mouse_y - y);					
				}

				if(mouse_hook){
					if (mouse_hook->GetFrame() != current_frame_uc){
						mouse_hook->Hook(mbtn[button]);
						mouse_hook->GetFrame()->FMMouseClick(mbtn[button], mouse_x - x, mouse_y - y);
					}
				}
			}
		}
	}

	//
	//	Handle Mouse Moving Events :
	//
	/*if (frame_under_cursor != current_frame_uc) {
		if (frame_under_cursor) {
			frame_under_cursor->FMMouseOut();
		}
		if (current_frame_uc) {
			current_frame_uc->FMMouseIn();
		}
	}*/
	
	//
	//	Mouse move
	//
	bool mouse_move = false;
	if (frame_under_cursor) {
		if (old_mouse.x!=mi->x && old_mouse.y!=mi->y) {
			float x, y;
			GetAbsolutePosition( current_frame_uc, x, y);
			uint btn = 0;
			if (mi->left)   btn |= UI_MOUSE_LEFT;
			if (mi->right)  btn |= UI_MOUSE_RIGHT;
			if (mi->middle) btn |= UI_MOUSE_MIDDLE;
			frame_under_cursor->FMMouseMove(btn, mi->x - x, mi->y - y);
			
			mouse_move = true;
		}
	}
	
	//
	//	Dragging stuff :
	//
	if (mb_down[0]) {
		BeginDragging(current_frame_uc, mi->x, mi->y);
	}
	
	if (mb_up[0] && drag_frame) {
		EndDragging();
	}
	
	//
	//	Update old values :
	//
	frame_under_cursor	=	current_frame_uc;	
	old_mouse			=	*mi;
}


void EUserInterface::BeginDragging(IUIFrame *frame, float x, float y)
{
	if (!frame) {
		return;
	}
	if (!frame->IsDraggable()) {
		return;
	}

	const float SB = 3.0f;
	drag_left   = drag_right = false;
	drag_bottom = drag_top   = false;

	if (frame->IsSizeable()) {
		uiRect_s r = frame->GetFrameRect();
		if (x >= r.x        && x <= r.x+SB)   drag_left   = true;
		if (x >= r.x+r.w-SB && x <= r.x+r.w)  drag_right  = true;
		if (y >= r.y        && y <= r.y+SB)   drag_top    = true;
		if (y >= r.y+r.h-SB && y <= r.y+r.h)  drag_bottom = true;
	}
	
	drag_start_rect	=	frame->GetFrameRect();
	drag_frame		=	frame;
	drag_start.x	=	(float)mouse_input.x;
	drag_start.y	=	(float)mouse_input.y;
	drag_current.x	=	drag_start.x;
	drag_current.y	=	drag_start.y;
}


void EUserInterface::EndDragging(void)
{
	if (!drag_frame) {
		return;
	}
	uiRect_s dr = GetDragRect();
	
	drag_frame->FMMove(dr.x, dr.y);
	drag_frame->FMResize(dr.w, dr.h);
	drag_frame = NULL;
}


uiRect_s EUserInterface::GetDragRect(void)
{
	const float MS = 8; // minimal size;
	if (drag_frame) {
		uiRect_s r;
		float dx = mouse_input.x - drag_start.x;
		float dy = mouse_input.y - drag_start.y;
		r = drag_start_rect;

		if ( !(drag_left||drag_right||drag_top||drag_bottom) ) {
			r.x += dx;
			r.y += dy;
		} else {
			if (drag_left) {
				if (dx>r.w-MS) dx = r.w - MS;
				r.x += dx;
				r.w -= dx; 
			}
			if (drag_right) {
				r.w += dx; 
			}
			if (drag_top) {
				if (dy>r.h-MS) dy = r.h - MS;
				r.y += dy;
				r.h -= dy; 
			}
			if (drag_bottom) {
				r.h += dy; 
			}
			if (r.w < MS) {	r.w = MS;	}
			if (r.h < MS) {	r.h = MS;	}
		}
		return r;
	} else {
		return uiRect_s(0,0,0,0);
	}
}


IUIFrame *EUserInterface::GetDraggingFrame(void) {
	return drag_frame;
}

/*-----------------------------------------------------------------------------
	Rendering stuff :
-----------------------------------------------------------------------------*/

//
//	EUserInterface::RenderFrames
//
void EUserInterface::RenderFrames(void)
{
	rs->Set2DViewMode(0, 0);
	rs->SetTransform(Matrix4Translate(EVec4(0,0,0,0)));
	
	uint w, h;
    rs->GetScreenSize(w, h);
    
    DrawFrameRecursive(ui_root, EVec4(1,1,1,1));

	// Debug cursor :
	if (ui_debug->Int()) {		
		float x = (float)mouse_input.x;
		float y = (float)mouse_input.y;
		rs->DrawRectOutline(x-7, y-7, 15, 15, EVec4(1,1,1,1));
	}
}


//
//	EUserInterface::DrawFrameRecursive
//	- each frame draws self relatively of parent client rect
//
void EUserInterface::DrawFrameRecursive(EUINode *node, EVec4 color)
{
	IUIFrame	*frame = node->frame;
	if (!frame->IsVisible()) {
		return;
	}

	float x, y;
	if (!node->GetParent()) {
		x = y = 0;
	} else {
		GetAbsolutePosition(node->GetParent()->frame, x, y);
	}
	
	rs->Set2DViewMode(0, 0);
	rs->SetTransform(Matrix4Translate(EVec4(x,y,0,0)));
	
	//SetBranchColor(EVec4(1,1,1, frame->GetFrameOpacity()));
	
	frame->FMPaint();
	
		if (ui_debug->Int()) {
			uiRect_s fr = frame->GetFrameRect();
			//uiRect_s cr = frame->GetClientRect();
			rs->DrawRectOutline(fr.x, fr.y, fr.w, fr.h, EVec4(1,1,1, 0.3f));
			//rs->DrawRectOutline(cr.x, cr.y, cr.w, cr.h, EVec4(1,1,1, 0.3f));
			
			if (GetFrameUnderCursor()==frame) {
				rs->DrawRectOutline(fr.x, fr.y, fr.w, fr.h, EVec4(1,1,1, 1.0f));
				string s = va("%s", typeid(*frame).name());
				DrawStringMT(fr.x+1, fr.y+9,  8, 8, "chars.tga", s.c_str(),				EVec4(1,1,1, 0.75));
				DrawStringMT(fr.x+1, fr.y+17, 8, 8, "chars.tga", frame->GetFrameText(), EVec4(1,1,1, 0.75));
				string s1 = va("%f %f %f %f", fr.x, fr.y, fr.w, fr.h);
				DrawStringMT(fr.x+1, fr.y+25, 8, 8, "chars.tga", s1.c_str(), EVec4(1,1,1, 0.75));
			}
		}
	
	for (uint i=0; i<node->GetChildNum(); i++) {	
		DrawFrameRecursive( node->GetChild(i), color );
	}
	
	//RevertBranchColor();

	//	Restore view :
	rs->Set2DViewMode(0, 0);
	rs->SetTransform(Matrix4Translate(EVec4(0,0,0,0)));
}


//
//	EUserInterface::ShowFrame
//
void EUserInterface::ShowFrame(IUIFrame *frame)
{
	if (FindFrameNode(frame)) {
		frame->FMShowFrame();
	}
}


//
//	EUserInterface::HideFrame
//
void EUserInterface::HideFrame(IUIFrame *frame)
{
	if (FindFrameNode(frame)) {
		frame->FMHideFrame();
	}
}


//
//	EUserInterface::ProcessFrames
//
void EUserInterface::ProcessFrames(void)
{
	ProcessFrameRecursive(ui_root);
}


//
//	EUserInterface::ProcessFrameRecursive
//
void EUserInterface::ProcessFrameRecursive(EUINode *node)
{
	node->frame->FMProcess(core->GetDeltaTime(), 0.001f * sys->Milliseconds());

	for (uint i=0; i<node->GetChildNum(); i++) {	
		ProcessFrameRecursive( node->GetChild(i) );
	}
}


//
//	EUserInterface::SetForegroundFrame
//
void EUserInterface::SetForegroundFrame(IUIFrame *frame)
{
	EUINode *node = FindFrameNode(frame);
	ASSERT(node);
	
	EUINode *parent = node->GetParent();
	ASSERT(parent);
	
	parent->MoveChildBack(node);
}


//
//	EUserInterface::SetActiveFrame
//
void EUserInterface::SetActiveFrame(IUIFrame *frame)
{
	if (!frame) {
		active_frame = NULL;
		return;
	}
	if (FindFrameNode(frame)) {
		active_frame = frame;
	}
}


//
//	EUserInterface::GetActiveFrame
//
IUIFrame *EUserInterface::GetActiveFrame(void)
{
	if (!FindFrameNode(active_frame)) {
		return NULL;
	}
	return active_frame;
}


static bool IsInRect(float cx, float cy, float x, float y, float w, float h)
{
	if (cx<x) return false;
	if (cy<y) return false;
	if (cx>x+w) return false;
	if (cy>y+h) return false;
	return true;
}


//
//	EUserInterface::GetFrameUnderCursor
//
IUIFrame *EUserInterface::GetFrameUnderCursor(void)
{
	float cur_x = (float)mouse_input.x;
	float cur_y = (float)mouse_input.y;

	EUINode	*top = ui_root;	
	
	_begin:
	//for (uint i=0; i<top->GetChildNum(); i++) 
	for (int i=top->GetChildNum()-1; i>=0; i--) 
	{
		// TODO : Check visibility!!!
		EUINode *child = top->GetChild(i);
		
		if (!child->frame->IsEnabled()) continue;
		
		float x,y,w,h;
		
		GetAbsolutePosition(child->frame, x, y);
		uiRect_s r = child->frame->GetFrameRect();
		w = r.w;
		h = r.h;
		
		if (IsInRect(cur_x, cur_y, x, y, w, h))
		{
			top = child;
			goto _begin;
		}
	}
	return top->frame;
}


//
//	EUserInterface::GetAbsolutePosition
//
void EUserInterface::GetAbsolutePosition(IUIFrame *frame, float &x, float &y)
{
	EUINode *node = FindFrameNode(frame);
	ASSERT(node);
	
	x = y = 0;
	
	while(node) {
		uiRect_s r = node->frame->GetFrameRect();
		x += r.x;
		y += r.y;
		node = node->GetParent();
	}
}


//
//	EUserInterface::FindFrameNode
//
EUINode *EUserInterface::FindFrameNode(IUIFrame *frame)
{
	return RecursiveSearch(ui_root, frame);
}


EUINode *EUserInterface::RecursiveSearch(EUINode *node, IUIFrame *frame)
{
	if (node->frame == frame) {
		return node;
	}
	
	for (uint i=0; i<node->GetChildNum(); i++) {
		EUINode *n = RecursiveSearch(node->GetChild(i), frame);
		if (n) {
			return n;
		}
	}
	
	return NULL;
}














